package com.njupt.StringProblem;

import java.util.Arrays;

/**
 * 541. 反转字符串 II
 * 给定一个字符串 s 和一个整数 k，从字符串开头算起，每计数至 2k 个字符，就反转这 2k 字符中的前 k 个字符。
 *
 * 如果剩余字符少于 k 个，则将剩余字符全部反转。
 * 如果剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符，其余字符保持原样。
 */
public class ReverseStr {
    public String reverseStr(String s, int k) {

        int num = s.length()%(2*k)==0 ? s.length()/(2*k) : s.length()/(2*k)+1;

        if(num==1 && s.length()<=k){
            return new StringBuffer(s).reverse().toString();
        }

        int startIndex=0;int endIndex = 0;
        for (int i = 0; i < num; i++) {
            startIndex = i*2*k;
            endIndex = i*2*k + k -1;
            if(endIndex>s.length()-1){
                int re = s.length()-startIndex;
                if(re<k){
                    s = reverseSub(s,startIndex,startIndex+re-1);
                }else {
                    s = reverseSub(s,startIndex,startIndex+k-1);
                }
            }else {
                s = reverseSub(s,startIndex,endIndex);
            }


        }

        return s;
    }

    public String reverseSub(String s,int startIndex,int endIndex){
        char[] charArray = s.toCharArray();
        char temp;
        while(true){
            temp = charArray[startIndex];
            charArray[startIndex] = charArray[endIndex];
            charArray[endIndex] = temp;
            startIndex++;
            endIndex--;
            if(startIndex>endIndex){
                break;
            }
        }
        return char2String(charArray);
    }

    public String char2String(char[] chars){
        StringBuffer stringBuffer = new StringBuffer();

        for (int i = 0; i < chars.length; i++) {
            stringBuffer.append(chars[i]);
        }
        return stringBuffer.toString();
    }


    //遍历数组的时候，直接从下标索引开始遍历
    public String reverseStr1(String s, int k){
        char[] charArray = s.toCharArray();
        int len = s.length();
        for (int i = 0; i < len; i +=2*k) {
            reverse(charArray,i,Math.min(i+k,len)-1);
        }


        return new String(charArray);
    }

    public void reverse(char[] arr,int startIndex,int endIndex){
        char temp;
        while(true){
            temp = arr[startIndex];
            arr[startIndex] = arr[endIndex];
            arr[endIndex] = temp;
            startIndex++;
            endIndex--;
            if(startIndex>endIndex){
                break;
            }
        }
    }

    public static void main(String[] args) {
        String s = "abcdefg";
        ReverseStr test = new ReverseStr();

        String s1 = test.reverseStr1(s, 3);
        System.out.println(s1);


    }
}
